<?php
/**
 * Created by 项目.
 * User: xuguopeng
 * Date: 5/26/21
 * Time: 5:18 PM
 */

namespace app\api\controller\v1;

use app\api\model\StoreUser as StoreUserModel;
use app\api\model\StoreUserItem;
use app\api\model\User as UserModel;
use app\api\model\UserInvitation;
use app\api\model\UserMoney;
use LinCmsTp5\exception\ParameterException;
use think\Db;
use think\Exception;
use app\api\model\Store as StoreModel;

// 店员
class StoreUser
{
    /**
     * 获取员工列表
     * @validate('PagingParameter')
     */
    public function getDataList($name,$store_id,$group_id,$type,$page,$limit)
    {
        $where = [];
        if($name) {
            $where[] = ['name','like','%'.$name.'%'];
        }
        if($store_id) {
            $where[] = ['store_id', 'eq', $store_id];
        }
        if($group_id) {
            $where[] = ['group_id', 'eq', $group_id];
        }
        if($type) {
            $where[] = ['type','eq',$type];
        }
        $query = StoreUserModel::where($where)->with('store,user,group')->order('id desc');
        $count = $query->count();
        $result = $query->page($page, $limit)->select()->each(function ($item){
            if($item['type'] == 1) {
                $item['type_name'] = '店长';
            } elseif($item['type'] == 2) {
                $item['type_name'] = '组长';
            } elseif($item['type'] == 3) {
                $item['type_name'] = '店员';
            } elseif($item['type'] == 4) {
                $item['type_name'] = '老板';
            }
        })->toArray();
        foreach ($result as $k=>$v){
            if($v['user']) {
                $result[$k]['user']['invite_money'] = 0;
                $inviteUser = UserInvitation::where('inviter',$v['id'])->where('type',2)->select()->toArray();
                if(count($inviteUser) > 0) {
                    $inviteUserIds =  array_column($inviteUser,'invitee');
                    if(count($inviteUserIds) > 0) {
                        $userMoney = UserMoney::where('user_id','in',$inviteUserIds)
                            ->where('status','eq',2)
                            ->select();
                        if(!$userMoney->isEmpty()) {
                            $userMoney = UserMoney::where('user_id','in',$inviteUserIds)
                                ->where('status','eq',2)
                                ->sum('money');
                            if($userMoney) {
                                $result[$k]['user']['invite_money'] = $userMoney;
                            }
                        }
                    }
                }
            }else{
                $result[$k]['user'] = [ 'invite_money' => 0 ];
            }
            if($v['type'] == 4) {
                $items = StoreUserItem::where('store_user_id',$v['id'])->with('store')->select()->toArray();
                $names = '';
                foreach ($items as $vo) {
                    $names .= $vo['store']['name'].'-';
                }
                $result[$k]['store']['name'] = $names;
            }
        }
        $data['count'] = $count;
        $data['data'] = $result;
        return $data;
    }

    /**
     * 获取店员详情
     *  @validate('IdMustBePositiveInt')
     */
    public function getDataInfo($id)
    {
        $info = StoreUserModel::get($id);
        if($info['type'] == 4) {
            $items = StoreUserItem::where('store_user_id',$id)->select()->toArray();
            $info['store_ids'] = array_column($items,'store_id');
        } else {
            $info['store_ids'] = [];
        }
        return $info;
    }

    /**
     * 修改店员信息
     * @validate('CheckStoreUser')
     */
    public function updateData($id,$name,$phone,$remarks,$desc,$store_id,$store_ids,$group_id,$type,$user_id)
    {
        if(!$group_id) {
            $group_id = null;
        }
        $info = StoreUserModel::where('id',$id)->find();
        $user = UserModel::where('id',$user_id)->find();
        if($info['user_id'] != $user['id']) {
            if ($user['type'] != 1) {
                throw new ParameterException([
                    'msg' => [
                        'store_user' => '该用户已经绑定角色'
                    ]
                ]);
            }
        }
        if($info) {
            if($type == 4) {
                $arr = [];
                foreach ($store_ids as $v){
                    $itemInfo = StoreUserItem::where('store_id',$v)->find();
                    if($itemInfo) {
                        if($itemInfo['store_user_id'] != $info['id']) {
                            $store = StoreModel::get($itemInfo['store_id']);
                            throw new ParameterException([
                                'msg' => [
                                    'store_user' => $store['name'].'已经绑定'
                                ]
                            ]);
                        }
                    }
                    array_push($arr,['store_id' => $v, 'store_user_id' => $info['id']]);
                }
            }
            Db::startTrans();
            try {
                StoreUserItem::destroy(['store_user_id' => $info['id']]);
                $info->name = $name;
                $info->phone = $phone;
                $info->desc = $desc;
                if($type == 4) {
                    $info->store_id = null;
                    $info->group_id = null;
                } else {
                    $info->store_id = $store_id;
                    $info->group_id = $group_id;
                }
                $info->type = $type;
                $info->user_id = $user_id;
                $info->remarks = $remarks;
                $info->save();
                if($type == 1) {
                    $user_type = 2;
                }elseif($type == 2){
                    $user_type = 3;
                }elseif($type == 3){
                    $user_type = 4;
                }elseif($type == 4) {
                    $user_type = 8;
                }
                UserModel::where('id',$user_id)->update([
                    'type'=> $user_type
                ]);
                if($type == 4) {
                    $StoreUserItem = new StoreUserItem();
                    $StoreUserItem->saveAll($arr);
                }
                Db::commit();
            }
            catch (\Exception $e){
                Db::rollback();
                throw new ParameterException([
                    'msg' => [
                        'product' => '修改失败!'
                    ]
                ]);
            }
        }
        return writeJson(202, [], '修改成功！');
    }


    /**
     * 删除员工信息
     * @validate('IdMustBePositiveInt')
     */
    public function deleteData($id)
    {
        $info = StoreUserModel::where('id',$id)->find();
        if($info) {
            $user_id = $info['user_id'];
            StoreUserModel::destroy($id);
            UserModel::where('id',$user_id)->update([
                'type' => 1,
                'store_id' => null
            ]);
        }
        return writeJson(203, [], '删除成功！');
    }
}